<?php

/**
 * 上线设备管理
 */
class Client
{
	protected static $clientId;

	protected static $timeout = 10;

	protected static $driver;

	/**
	 * 取号
	 * @return int
	 */
	public static function getClientId()
	{
		if (!self::$clientId) {
			$file = ROOT_PATH. 'runtime/clientId.txt';
			if (file_exists($file)) {
				self::$clientId = file_get_contents($file);
			}
			if (!self::$clientId) {
				self::$clientId = (int) get_incr_id();
				file_put_contents($file, self::$clientId);
			}
		}
		return self::$clientId;
	}

	public static function setDriver($driver)
	{
		static::$driver = $driver;
	}

	public static function getDriver()
	{
		return static::$driver;
	}

	/**
	 * 设备上线
	 */
	public static function doOnline(array $params = [])
	{
		$clientId = static::getClientId();
		$params['client_id'] = $clientId;
		$params['last_time'] = time();
		redis()->hSet('1bom_online_client', $clientId, json_encode($params));
	}

	/**
	 * 设备定时刷新在线状态
	 * @return int
	 */
	public static function doRefresh()
	{
		$redis = redis();
		$clientId = static::getClientId();
		$clientArr = static::getClient($clientId);
		if (!$clientArr) {
			return 0;
		}
		$clientArr['last_time'] = time();
		return $redis->hSet('1bom_online_client', $clientId, json_encode($clientArr));
	}

	/**
	 * 获取指定的设备，不管它是否在线
	 * @param int|null $clientId 不设置就获取当前设备
	 * @return array|null
	 */
	public static function getClient($clientId = null)
	{
		$redis = redis();
		$clientId = $clientId ?: static::getClientId();
		$dataStr = (string) $redis->hGet('1bom_online_client', $clientId);
		if (!$dataStr) {
			return null;
		}
		return json_decode($dataStr, true);
	}

	/**
	 * 获取指定的在线设备，如果不在线就删除它
	 * @param $clientId
	 * @return array|null
	 */
	public static function getOnline($clientId)
	{
		$redis = redis();
		$clientArr = static::getClient($clientId);
		if (!is_array($clientArr)) {
			return null;
		}
		if (!isset($clientArr['last_time']) || (time() - $clientArr['last_time'] > static::$timeout)) {
			$redis->hDel('1bom_online_client', $clientId);
			return null;
		}
		return $clientArr;
	}

	/**
	 * 获取所有在线设备，删除登录超时的设备
	 * @param true|false $onlyClientId 是否只返回设备ID
	 * @return array|int[]|string[]
	 */
	public static function getOnlineAll($onlyClientId = false)
	{
		$redis = redis();
		$data = $redis->hGetAll('1bom_online_client');
		if (!$data) {
			return [];
		}
		$time = time();
		$offline = 0;
		foreach ($data as $clientId => $value) {
			$value = trim((string)$value);
			$value = json_decode($value, true);
			//删除登录超时的设备
			if (!is_array($value) || !isset($value['last_time']) || ($time - $value['last_time'] > static::$timeout)) {
				$offline++;
				unset($data[$clientId]);
				$redis->hDel('1bom_online_client', $clientId);
				continue;
			}
			$data[$clientId] = $value;
		}
		if ($onlyClientId) {
			return array_keys($data);
		}
		return $data;
	}
}
